package jym.tan.movielibrary.component.listener;

import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import jym.tan.movielibrary.component.ui.table.model.MovieSearchResultTableModel;
import jym.tan.movielibrary.factory.ComponentFactory;
import jym.tan.movielibrary.factory.ModelFactory;

public class MovieSearchResultTableSelectionListener implements ListSelectionListener {

	@Override
	public void valueChanged(ListSelectionEvent e) {
		ListSelectionModel listSelectionModel = (ListSelectionModel) e.getSource();
		if(listSelectionModel.getValueIsAdjusting()) {
			return;
		}
		
		int selectedRow = -1;
		if (!listSelectionModel.isSelectionEmpty()) {
			int minIndex = listSelectionModel.getMinSelectionIndex();
			int maxIndex = listSelectionModel.getMaxSelectionIndex();
			for (int i = minIndex; i <= maxIndex; i++) {
				if (listSelectionModel.isSelectedIndex(i)) {
					selectedRow = i;
					break;
				}
			}
		}		
		
		if(selectedRow != -1) {
			ComponentFactory.getMovieSearchInfoPanel().update(((MovieSearchResultTableModel) ModelFactory.getMovieSearchResultTableModel()).getMovieSearchModels().get(ComponentFactory.getMovieSearchResultTable().convertRowIndexToModel(selectedRow)));
		}
	}
}
